﻿using System.ComponentModel.DataAnnotations;
using System.Reflection;
namespace GSQ.BusinessEntities.Validation
{
   public  class ValidationEngine
    {
        public static bool Validate<T>(T item) where T : EntityBase
        {
            var properties = item.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);

            foreach (var property in properties)
            {
                var customAtt = property.GetCustomAttributes(typeof(ValidationAttribute), true);

                foreach (var att in customAtt)
                {
                    var valAtt = att as ValidationAttribute;
                    if (valAtt == null) continue;
                    object o = property.GetValue(item, null);
                    if (valAtt.IsValid(property.GetValue(item, null))) continue;
                                       
                    var brokenRule = new BrokenRule
                    {                        
                        Message = valAtt.ErrorMessage,
                        PropertyName = property.Name
                    };
                    item.BrokenRules.Add(brokenRule);
                }
            }
            return (item.BrokenRules.Count == 0);
        }
    }
}
